package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderInfoFeignClient;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author 李旭
 * @date 2021/12/4 15:08
 * @Description:
 */
@Service
public class PaymentInfoServiceImpl implements PaymentInfoService {


    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    @Autowired
    private OrderInfoFeignClient orderInfoFeignClient;
    @Autowired
    private RabbitService rabbitService;

    //生成支付表
    @Override
    public PaymentInfo insertPaymentInfo(Long orderId, PaymentType paymentType) {
        //防止 幂等性问题
        //1:查询 看看是否已经有此订单的支付表了
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("order_id", orderId));
        if (null == paymentInfo) {
            //1.1: 没有生成支付表
            paymentInfo = new PaymentInfo();
            OrderInfo orderInfo = orderInfoFeignClient.getOrderInfo(orderId);
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(paymentType.name());
            //银行流水： 支付成功之后 银行才会产生流水 暂时没有
            paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
            paymentInfo.setSubject(orderInfo.getTradeBody());
            paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
            paymentInfo.setCreateTime(new Date());
            //回调时间  回调信息 暂时没有
            paymentInfoMapper.insert(paymentInfo);
        } else {
            //1.2: 有 更新支付表中 支付方式 （支付宝 、微信）  时间
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfo.setCreateTime(new Date());
            paymentInfoMapper.updateById(paymentInfo);
        }
        return paymentInfo;
    }

    //更新支付表
    @Override
    public void update(Map<String, String> paramsMap) {
        /**
         * {
         *   gmt_create=2021-12-06 15:19:03,
         *   charset=utf-8,
         *   gmt_payment=2021-12-06 15:19:13,
         *   notify_time=2021-12-06 15:19:14,
         *   subject=Apple iPhone 11 (A2223) 128GB 黑色 移动联通电信4G手机 双卡双待 Apple iPhone 11 (A2223) 256GB 红色 移动联通电信4G手机 双卡双待 Ap,
         *   buyer_id=2088102181130586,
         *   invoice_amount=126979.00,
         *   version=1.0,
         *   notify_id=2021120600222151913030580519730851,
         *   fund_bill_list=[{
         *   "amount":"126979.00",
         *   "fundChannel":"ALIPAYACCOUNT"}],
         *   notify_type=trade_status_sync,
         *   out_trade_no=qwwewrrdd16789598851723qwee,
         *   total_amount=126979.00,
         *   trade_status=TRADE_SUCCESS,
         *   trade_no=2021120622001430580501836492,
         *   auth_app_id=2016102100732915,
         *   receipt_amount=126979.00,
         *   point_amount=0.00,
         *   app_id=2016102100732915,
         *   buyer_pay_amount=126979.00,
         *   seller_id=2088102180533564}
         */
        //防止幂等性问题   防止重复更新
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("out_trade_no", paramsMap.get("out_trade_no")));
        if(null != paymentInfo && PaymentStatus.UNPAID.name().equals(paymentInfo.getPaymentStatus())){
            //支付中 改已支付
            paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
            paymentInfo.setTradeNo(paramsMap.get("trade_no"));
            try {
                paymentInfo.setCallbackTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                   .parse(paramsMap.get("notify_time")));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            paymentInfo.setCallbackContent(JSONObject.toJSONString(paramsMap));
            paymentInfoMapper.updateById(paymentInfo);

            //发消息  保存最终一致性 事务问题 更新订单表
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,
                    MqConst.ROUTING_PAYMENT_PAY,paymentInfo.getOrderId());

        }


    }
}
